package com.xinlan.imageeditlibrary.editimage.fragment;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.xinlan.imageeditlibrary.BaseEditFragment;
import com.xinlan.imageeditlibrary.EditImageFragment;
import com.xinlan.imageeditlibrary.R;
import com.xinlan.imageeditlibrary.editimage.ModuleConfig;
import com.xinlan.imageeditlibrary.editimage.adapter.LvJingAdapter;
import com.xinlan.imageeditlibrary.editimage.fliter.PhotoProcessing;
import com.xinlan.imageeditlibrary.editimage.model.OnBackPressedCallBack;
import com.xinlan.imageeditlibrary.editimage.model.SpacesItemDecoration;
import com.xinlan.imageeditlibrary.editimage.utils.BaseUtils;
import com.xinlan.imageeditlibrary.editimage.utils.DensityUtil;

import java.io.IOException;


/**
 * 滤镜列表fragment
 *
 * @author panyi
 */
public class FilterListFragment extends BaseEditFragment {
    public static final int INDEX = ModuleConfig.INDEX_FILTER;
    public static final String TAG = FilterListFragment.class.getName();

    private Bitmap fliterBit;// 滤镜处理后的bitmap
    public static final String STICKER_FOLDER = "filters";
    private String[] fliters;
    private Bitmap currentBitmap;// 标记变量
    private EditImageFragment mEditImageFragment;
    private OnBackPressedCallBack mOnBackCall;
    private RecyclerView mRvLvJing;
    private String[] files;
    private LvJingAdapter mLvJingAdapter;
    private PopupWindow mPopLvJing;
    private View mMainView;
    private boolean isComplete;

    public static FilterListFragment newInstance(EditImageFragment mEditImageFragment) {
        FilterListFragment fragment = new FilterListFragment();
        fragment.setEditImageFragment(mEditImageFragment);
        fragment.setOnBackClick();
        return fragment;
    }


    public OnBackPressedCallBack getOnBackCall() {
        return mOnBackCall;
    }

    public void setOnBackClick() {
        mOnBackCall = new OnBackPressedCallBack() {
            @Override
            public void onBack() {
                backToMain();
            }
        };
    }

    public void setEditImageFragment(EditImageFragment mEditImageFragment) {
        this.mEditImageFragment = mEditImageFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.fragment_edit_image_fliter, null);
        return mMainView;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        View mPopView = getLayoutInflater().inflate(R.layout.popup_lvjing, null);
        mRvLvJing = mPopView.findViewById(R.id.rv_lvjing);
        mPopLvJing = BaseUtils.showPopwindow(activity, mPopView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        initLJFile();
        mRvLvJing.addItemDecoration(new SpacesItemDecoration(DensityUtil.dip2px(requireContext(), 15)));
        mLvJingAdapter = new LvJingAdapter(fliters, files, getLayoutInflater(), getActivity());
        mRvLvJing.setAdapter(mLvJingAdapter);
        mLvJingAdapter.setOnLvJingClickListener(new LvJingAdapter.OnLvJingClickListener() {
            @Override
            public void onLvJingClick(int pos) {
                onClick(pos);
            }
        });
        mPopView.findViewById(R.id.tv_hidepop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isComplete = true;
                mPopLvJing.dismiss();
                mLvJingAdapter.clearSelectList();
                applyFilterImage(true);
            }
        });
        mPopView.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isComplete = false;
                mPopLvJing.dismiss();

            }
        });
        mPopLvJing.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isComplete) {
                    isComplete = false;//这里设置为false 为了防止点击空白处消失时 isComplete 为 true
                    return;
                }
                mLvJingAdapter.clearSelectList();
                backToMain();
            }
        });
    }

    private void initLJFile() {
        try {
            fliters = getResources().getStringArray(R.array.filters);
            files = getActivity().getAssets()
                    .list(STICKER_FOLDER);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onShow() {
        mEditImageFragment.mode = EditImageFragment.MODE_FILTER;
        mPopLvJing.showAtLocation(mMainView, Gravity.BOTTOM, 0, 0);
        mLvJingAdapter.setOldBitmap(mEditImageFragment.getMainBit());
        mEditImageFragment.mFilterListFragment.setCurrentBitmap(mEditImageFragment.getMainBit());
        mEditImageFragment.mainImage.setImageBitmap(mEditImageFragment.getMainBit());
        //mEditImageFragment.mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        mEditImageFragment.mainImage.setScaleEnabled(false);
//        mEditImageFragment.bannerFlipper.showNext();
    }

    /**
     * 返回主菜单
     */
    @Override
    public void backToMain() {
        if (mPopLvJing != null && mPopLvJing.isShowing())
            mPopLvJing.dismiss();
        currentBitmap = mEditImageFragment.getMainBit();
        fliterBit = null;
        mEditImageFragment.mainImage.setImageBitmap(mEditImageFragment.getMainBit());// 返回原图
        mEditImageFragment.mode = EditImageFragment.MODE_NONE;

        mEditImageFragment.swFragment(0);
        mEditImageFragment.mainImage.setScaleEnabled(true);
//        mEditImageFragment.bannerFlipper.showPrevious();
    }

    /**
     * 保存滤镜处理后的图片
     */
    public void applyFilterImage(boolean isToMain) {
        if (currentBitmap == mEditImageFragment.getMainBit()) {// 原始图片
            if (isToMain)
                backToMain();
        } else {
            // 经滤镜处理后的图片
            mEditImageFragment.changeMainBitmap(fliterBit, true);
            if (isToMain)
                backToMain();
        }
    }

    @Override
    public void onDestroy() {
        if (fliterBit != null && (!fliterBit.isRecycled())) {
            fliterBit.recycle();
        }
        super.onDestroy();
    }

    /**
     * 选择滤镜效果
     */
    public void onClick(int position) {
        if (position == 0) {// 原始图片效果
            mEditImageFragment.mainImage.setImageBitmap(mEditImageFragment.getMainBit());
            currentBitmap = mEditImageFragment.getMainBit();
            return;
        }
        // 滤镜处理
        ProcessingImage task = new ProcessingImage();
        task.execute(position);
    }

    /**
     * 图片滤镜处理任务
     *
     * @author panyi
     */
    private final class ProcessingImage extends AsyncTask<Integer, Void, Bitmap> {
        private Bitmap srcBitmap;

        @Override
        protected Bitmap doInBackground(Integer... params) {
            int type = params[0];
            if (srcBitmap != null && !srcBitmap.isRecycled()) {
                srcBitmap.recycle();
            }

            srcBitmap = Bitmap.createBitmap(mEditImageFragment.getMainBit().copy(
                    Bitmap.Config.ARGB_8888, true));
            return PhotoProcessing.filterPhoto(srcBitmap, type);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (result == null)
                return;
            if (fliterBit != null && (!fliterBit.isRecycled())) {
                fliterBit.recycle();
            }
            fliterBit = result;
            mEditImageFragment.mainImage.setImageBitmap(fliterBit);
            currentBitmap = fliterBit;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

    }// end inner class

    public Bitmap getCurrentBitmap() {
        return currentBitmap;
    }

    public void setCurrentBitmap(Bitmap currentBitmap) {
        this.currentBitmap = currentBitmap;
    }


}// end class
